<?php
class DeliveryReturnsController extends AppController {

    var $name = 'DeliveryReturns';
    var $pageTitle = 'Delivery Request Return';
    var $viewPath = 'customers/returns/delivery';
    var $uses = array('DeRtH', 'DeRH', 'DeR', 'Customer', 'Site', 'RunningNo');
    var $paginate = array(
        'DeRtH' => array(
            'order' => 'DeRtH.id DESC'
        )
    );
    var $components = array('Email');

    const DELIVERY_RETURN_TYPE = 'RT';

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'main_cust_returns');
    }

    function display() {
        parent::display('DeRtH');
        $this->paginate['DeRtH']['contain'] = array('Supplier', 'DeRtStatus', 'DeRH');

        $this->_checkSite('DeRtH');
        $this->_checkBetweenSearch('DeRtH', 'return_date');
        $this->_paging('DeRtH');
    }

    function save() {
        $is_success = true;
        $id = null;

        // เรียงลำดับรายการใหม่ กรณีลบแถว Index เปลี่ยน
        $this->adjustRowIndex($this->data['DeRt']);

        // ตรวจสอบว่ามีสินค้าอยู่ในใบ ItsStockInHead
        if (count($this->data['DeRt']) == 0) {
            $this->Session->setFlash("You didn't have any return product!", 'flash/fail');
            $is_success = false;
            unset($this->data);
        } else {
            $this->DeRtH->query("BEGIN");
            $collector_id = $this->Auth->user('id');
            $customer_id = $this->Auth->user('customer_id');
            $site_id = $this->Auth->user('site_id');

            // กำหนดข้อมูล Cust Stock out Return Head
            // Generate return no
            $this->Customer->id = $this->Auth->user('customer_id');
            $cust_no = $this->Customer->field('cust_no');
            $this->Site->id = $this->Auth->user('site_id');
            $site_no = $this->Site->field('site_no');
            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::DELIVERY_RETURN, $year, $customer_id);
            $this->data['DeRtH']['return_no'] = $cust_no . '-' . $site_no . '-' . RunningNo::DELIVERY_RETURN . '-' . $year . $runno;
            $this->data['DeRtH']['customer_id'] = $this->Auth->user('customer_id');
            $this->data['DeRtH']['site_id'] = $this->Auth->user('site_id');
            $this->data['DeRtH']['collector_id'] = $this->Auth->user('id');
            $this->data['DeRtH']['delivery_return_status_id'] = DeRtStatus::RETURNING;

            if ($this->DeRtH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                // update DeRH ว่ามีการ Return
                $this->DeRH->id = $this->data['DeRtH']['delivery_request_head_id'];
                $this->DeRH->saveField('is_returned', true);

                $id = $this->DeRtH->id;
            } else {
                $is_success = false;
            }
        }

        if ($is_success) {
            $id = $this->DeRtH->id;
            $this->DeRtH->query("COMMIT");
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->DeRtH->query("ROLLBACK");
            $this->Session->setFlash("Save fail !", 'flash/fail');
        }

        $this->data['DeRt'] = null;
        $this->setAction('view', $id);
    }

    function view($id = null) {
        // mode edit
        if ($id != null) {
            $this->DeRtH->contain(array('Customer', 'Site', 'DeRH', 'Supplier', 'DeRtStatus',
                'DeRt' => array('Product' => array('Unit'), 'CustProductSite')));
            $this->data = $this->DeRtH->findById($id);

            $this->_neighbors($id, $this->DeRtH, array('fields' => array('id', 'return_no')));
            $this->set('mode', 'edit');
        } elseif (isset($this->passedArgs['delivery_request_head_id'])) {
            // มาจากหน้า Delivery Request
            $this->DeRtH->contain(array('Customer', 'Site', 'DeRH', 'Supplier', 'DeRtStatus',
                'DeRt' => array('Product' => array('Unit'), 'CustProductSite')));
            $this->data = $this->DeRtH->findByDeliveryRequestHeadId($this->passedArgs['delivery_request_head_id']);

            $this->_neighbors($id, $this->DeRtH, array('fields' => array('id', 'return_no')));
            $this->set('mode', 'edit');
        } else {
            $this->set('deRHs', $this->DeRH->find('list', array(
                        'conditions' => array(
                            'DeRH.site_id' => $this->Auth->user('site_id'),
                            // เฉพาะใบที่ยังไม่ถูก return, invoice
                            'DeRH.is_returned' => false,
                            'DeRH.is_invoiced' => false,
                            // แสดง เฉพาะ DR ที่ received หรือ released แล้วเท่านั้น
                            'DeRH.delivery_request_status_id >=' => DeRStatus::RECEIVED
                        ),
                        'order' => 'id DESC'
                            )
                    )
            );
            $this->set('return_by', $this->Auth->user('name'));
            $this->set('today', date("d/m/Y"));
            $this->set('mode', 'add');
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->DeRtH->contain(array('Supplier', 'Customer', 'Site', 'DeRH', 'DeRtStatus', 'DeRt' => array('Product' => array('Unit'), 'CustProductSite')));
        $this->data = $this->DeRtH->findById($id);
    }

    function json_find_by_id($id) {
        $this->layout = 'ajax';
        $this->viewPath = 'elements/ajax';
        $this->RequestHandler->setContent('json');

        $this->DeRH->contain(array('Customer', 'Site', 'Supplier', 'DeRStatus',
            'DeR' => array('Product', 'CustProductSite')));
        $data = $this->DeRH->findById($id);

        $this->set('data', $data);
        $this->render('json');
    }

    function json_find_by_part_no_delivery_request_head_id() {
        $this->layout = 'ajax';

        // ค้นหาข้อมูลโดย part no และ dispatch id
        $this->DeR->contain(array('Product' => array('Unit'), 'CustProductSite'));
        $data = $this->DeR->find('first', array('conditions' => array(
                        'OR' => array(
                            'Product.part_no' => $this->data['part_no'],
                            'Product.supplier_part_no' => $this->data['part_no'],
                            'CustProductSite.stock_code' => $this->data['part_no'],
                        ),
                        'delivery_request_head_id' => $this->data['delivery_request_head_id'],
                        'receive_qty >' => 0
                        ))
        );

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }

}

?>